var fs = require('fs'); 
var path = require('path');
var constVar = require('./src/constVar');
var pack = require('./src/pack');

/**递归某个路径，找出该路径下需要处理得png数据 */
function findPack(srcPath,packDic){
    let fileArr = fs.readdirSync(srcPath);
    fileArr.forEach((fileName)=>{
        let filePath = path.join(srcPath,fileName);
        let stat = fs.statSync(filePath);
        if(stat.isFile()){
            if(path.extname(fileName)=='.png' && fileName.indexOf(constVar.packName)==-1){
                if(!packDic[srcPath])
                    packDic[srcPath] = [];
                packDic[srcPath].push(filePath);
            }
        }else if(stat.isDirectory()){
            findPack(filePath,packDic);
        }
    });
}

/**png剪切合成 */
async function pngCutPack(folder,option){
    if(!option)
        option = {};
    if(!fs.existsSync(folder)){
        console.log('路径：'+folder+'不存在');
        return;
    }
    let stat = fs.statSync(folder);
    if(!stat.isDirectory()){
        console.log('不是一个路径:'+folder);
        return;
    }
    let packDic = {};
    findPack(folder,packDic);
    let packArr = [];
    for(let k in packDic){
        packArr.push(packDic[k]);
    }
    let maxDealNum = 10;
    let num = 0;
    let flag = true;
    console.time('pngCutPackTime');
    while(flag){
        let arr = [];
        let len = maxDealNum+num;
        for(let i=num;i<len;i++){
            let pngPathArr = packArr[i];
            if(pngPathArr){
                arr.push(pack(pngPathArr));
                num++;
            }else{
                flag = false;
                break;
            }
        }
        await Promise.all(arr);
    }
    console.timeEnd('pngCutPackTime');
}
module.exports = pngCutPack;